
import json
import collections
import os, re

def load(file):
    with open(file,'r',encoding='utf-8-sig') as f:
        data = json.load(f)
        return data

def get_paths(source):
    paths = []
    if isinstance(source, collections.MutableMapping):  # found a dict-like structure...
        for k, v in source.items():  # iterate over it; Python 2.x: source.iteritems()
            paths.append([k])  # add the current child path
            paths += [[k] + x for x in get_paths(v)]  # get sub-paths, extend with the current
    # else, check if a list-like structure, remove if you don't want list paths included
    elif isinstance(source, collections.Sequence) and not isinstance(source, str):
        # Python 2.x: use basestring instead of str ^
        for i, v in enumerate(source):
            paths.append([i])
            paths += [[i] + x for x in get_paths(v)]  # get sub-paths, extend with the current
    return paths

def dump_path(j):
    fo = open("e:\\path_output.txt", 'w' ,encoding='utf8')
    ps = get_paths(j)
    for p in ps:
        fo.write("/".join(str(i) for i in p[1:])+"\n")
    fo.close()

def dump_one_file(filename):
    dump_pos_list = False
    
    if dump_pos_list is False:
        fo = open("e:\\"+filename+".csv", 'w' ,encoding='utf8')
    else:
        fo = open("e:\\"+"pos_list"+".csv", 'a+' ,encoding='utf8')
     
    j=load("E:\w\\"+filename+".json")
    
    #return dump_path(j)
    
    pos_ll = {  
        "adjective"               : "adj.",
        "adverb"                  : "adv.",
        "auxiliary verb"          : "aux.v.",
        "intransitive verb"       : "vi.",
        "noun"                    : "n.",
        #"noun plural"             : "",
        "possessive noun"         : "n.",
        "proper noun"             : "n.",
        #"proper noun plural"      : "",
        "proper possessive noun"  : "n.",
        "transitive verb"         : "vt.",
        "verb"                    : "v.",
    }


    for word, defi in j.items():

        # 去掉这些字符
        if re.search("^[a-z]+$", word) is None:
            continue
            
        pos_list = []
        for p, p2 in pos_ll.items():
            if defi.get(p.strip()):
                pos_list.append(p2)            

        pos_list = list(set(pos_list))
        pos_str = "#".join(p.strip().lower() for p in pos_list)

        if len(pos_str) > 0:
            fo.write(word+"|"+pos_str+"\n")
            #fo.write(word+"|"+pos_str+"|"+form_str+"|"+"\n")
            #fo.write(pos_str+"\n")
            #fo.write(form_str+"\n")
            pass



    fo.close()

#=============================
files = [
    "wordnik_20200221                   ",
]

for file in files:
    dump_one_file(file.strip())